package com.hudson.codec.hudson.utils;

import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class CodecUtil {

    /**
     * 写入字符串到ByteBuf
     */
    public static void writeString(ByteBuf out, String str) {
        if (str == null) {
            out.writeInt(-1); // -1表示null
            return;
        }

        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        out.writeInt(bytes.length);
        out.writeBytes(bytes);
    }

    /**
     * 从ByteBuf读取字符串
     */
    public static String readString(ByteBuf in) {
        int length = in.readInt();
        if (length == -1) {
            return null;
        }

        if (length == 0) {
            return "";
        }

        byte[] bytes = new byte[length];
        in.readBytes(bytes);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * 写入字符串到ByteBuf
     */
    public static void writeExtData(ByteBuf out, Map<String, String> extFields) {
        if (extFields == null || extFields.isEmpty()) {
            out.writeInt(0); // map大小为0
        } else {
            out.writeInt(extFields.size());
            for (Map.Entry<String, String> entry : extFields.entrySet()) {
                CodecUtil.writeString(out, entry.getKey());
                CodecUtil.writeString(out, entry.getValue());
            }
        }
    }

    /**
     * 从ByteBuf读取字符串
     */
    public static Map<String, String> readExtData(ByteBuf in) {
        int mapSize = in.readInt();
        Map<String, String> extFields = new HashMap<>();
        if (mapSize > 0) {
            extFields = new HashMap<>(mapSize);
            for (int i = 0; i < mapSize; i++) {
                String key = CodecUtil.readString(in);
                String value = CodecUtil.readString(in);
                extFields.put(key, value);
            }
        }
        return extFields;
    }
}
